package com.jiangzhuolin.admin.controller;

import com.jiangzhuolin.admin.dao.UserRepository;
import com.jiangzhuolin.admin.pojo.User;
import com.jiangzhuolin.admin.util.MyPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class IndexController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private MyPasswordEncoder myPasswordEncoder;

    @RequestMapping("/")
    public String hello () {
        return "Hello Spring Boot";
    }

    @RequestMapping("/hello")
    public String helloSecurity () {
        return "Hello Spring Security";
    }

    @RequestMapping("/adminRole")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String adminRole () {
        return "ADMIN Role";
    }

    @PostMapping("/registry")
    public String registry(User user) {
        try {
            userRepository.save(new User(user.getUsername(), myPasswordEncoder.encode(user.getPassword())));
            return "注册成功！";
        } catch (Exception e) {
            return "注册失败！";
        }


    }
}
